<template>
<main>
    <el-form ref="ruleFormRef" style="max-width: 37.5rem" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm">
        <el-form-item label="文章发布" prop="title">
            <el-input v-model="ruleForm.title" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="是否公开" prop="isOpen">
            <el-switch v-model="ruleForm.isOpen" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
            <textarea v-model="ruleForm.content"></textarea>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                Submit
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>
    </el-form>
</main>
</template>

<script lang="ts" setup>
import {
    reactive,
    ref
} from 'vue'
import type {
    FormInstance,
    FormRules
} from 'element-plus'
import axios from 'axios';

const ruleFormRef = ref < FormInstance > ()

const check = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('Please input the right content'))
    }
    callback()

}

const ruleForm = reactive({
    title: '',
    isOpen: false,
    content: '',
})

const rules = reactive < FormRules < typeof ruleForm >> ({
    title: [{
        validator: check,
        trigger: 'blur'
    }],
    content: [{
        validator: check,
        trigger: 'blur'
    }],
})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {

            //   http://localhost:8080/posts
            axios.post('http://localhost:8080/posts', {
                title: ruleForm.title,
                content: ruleForm.content,
                status: ruleForm.isOpen,
            }).then(r => {
                console.log(r.data);

            })
            console.log('submit!')
        } else {
            console.log('error submit!')
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style scoped>
main {
    width: 100vw;
    height: fit-content;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

}
</style>
